<script lang="jsx">
import _ from 'lodash'
import { onMounted, reactive, ref } from '@vue/composition-api'
import { request } from '../../utils/request'

export default {
  props: {
    detail: {
      type: Object,
      required: true
    },
    sections: {
      type: Array,
      required: true
    }
  },
  setup(props) {
    const { detail, sections } = props

    const loading = ref(true)

    const sectionData = reactive({})

    async function initSectionData() {
      await Promise.all(sections.map(async section => {
        sectionData[section.id] = await getData(section)
      }))
    }

    async function getData(section) {
      // Select
      if (section.select) {
        return Promise.resolve(section.select(detail))
      }
      if (section.fetch) {
        return await request(section.fetch, {
          params: {
            enterpriseId: detail.id
          }
        })
      }
      return null
    }

    onMounted(async () => {
      await initSectionData()
      loading.value = false
    })

    return {
      loading,
      sectionData
    }
  },
  render(h) {
    const { loading, sections, sectionData } = this

    if (loading) {
      return <div>Loading</div>
    }

    const components = sections.map(section => {
      const data = section.mock && _.isEmpty(sectionData[section.id])
          ? section.mock
          :sectionData[section.id]

      if (!data) {
        return null
      }

      const commonProps = {
        section,
        title: section.label,
        data
      }

      const tableProps = {}
      if (section.columns) {
        tableProps.columns = section.columns
      }

      return h(section.component, {
        props: {
          ...commonProps,
          ...tableProps
        }
      })
    })

    return (
      <div>
        {components}
      </div>
    )
  }
}
</script>
